import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'lodash';
import { Button, Input, Dropdown, Menu, message, Popover, Radio, Row, Col } from 'antd';
import { config } from '@/config/index';
import ChatMessage from '@/components/Chat/ChatMessage';
import WebIM from '@/config/WebIM';
import './WebIm.less';
import { CalendarFilled, FileImageFilled } from '@ant-design/icons';
import TextArea from 'antd/lib/input/TextArea';
// const rtc = WebIM.rtc;
const { PAGE_NUM } = config;

const chatType = {
  contact: 'chat',
  group: 'groupchat',
  chatroom: 'chatroom',
  stranger: 'stranger',
};

class Chat extends React.Component {
  input = null; // eslint-disable-line
  image = null; // eslint-disable-line
  timer = null;

  constructor({ match }) {
    super();
    // const { selectTab, selectItem = '' } = match.params
    this.state = {
      showWebRTC: false,
      selectTab: 0,
      selectItem: '',
      value: '',
      isLoaded: false,
      visible: false,
      checkedValue: '',
      showUserInfoMoadl: false,
      offset:0,
      footHeight:'15vh'
    };
    this.userInfo = {};
    this.showEdit = false;
    this.handleSend = this.handleSend.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.pictureChange = this.pictureChange.bind(this);
    this.fileChange = this.fileChange.bind(this);
    // this.handleEmojiSelect = this.handleEmojiSelect.bind(this)
    // this.handleEmojiCancel = this.handleEmojiCancel.bind(this)
    this.handleKey = this.handleKey.bind(this);
    // this.handleRightIconClick = this.handleRightIconClick.bind(this)
    this.onMenuContactClick = this.onMenuContactClick.bind(this);

    // this.logger = WebIM.loglevel.getLogger('chat component')
  }

  scollBottom() {
    if (!this._not_scroll_bottom) {
      setTimeout(() => {
        const dom = this.refs['x-chat-content'];
        if (!ReactDOM.findDOMNode(dom)) return;
        dom.scrollTop = dom.scrollHeight;
      }, 0);
    }
  }

  pictureChange(e) {
    const { match } = this.props;
    const { selectItem, selectTab } = match && match.params;
    const isRoom = chatType[selectTab] == 'chatroom' || chatType[selectTab] == 'groupchat';

    const file = WebIM.utils.getFileUrl(e.target);

    if (!file.filename) {
      this.image.value = null;
      return false;
    }

    if (!config.imgType[file.filetype.toLowerCase()]) {
      this.image.value = null;
      // todo i18n
      return message.error(`不支持此类型: ${file.filetype}`, 1);
    }

    this.props.sendImgMessage(chatType[selectTab], selectItem, { isRoom }, file, () => {
      this.image.value = null;
    });
  }

  fileChange(e) {
    const { match } = this.props;
    const { selectItem, selectTab } = match && match.params;
    const isRoom = chatType[selectTab] == 'chatroom' || chatType[selectTab] == 'groupchat';

    const file = WebIM.utils.getFileUrl(e.target);

    if (!file.filename) {
      this.file.value = null;
      return false;
    }

    this.props.sendFileMessage(chatType[selectTab], selectItem, { isRoom }, file, () => {
      this.file.value = null;
    });
  }

  handleChange(e) {
    const v = e.target.value;
    const splitValue = this.state.value ? this.state.value.split('') : [];
    splitValue.pop();
    if (v == splitValue.join('')) {
      // this.handleEmojiCancel()
    } else {
      this.setState({
        value: v,
      });
    }
  }

  handleSend(e) {
    const { match, message } = this.props;
    const { selectItem, selectTab } = match && match.params;
    const { value } = this.state;
    if (!value) return;
    this.props.sendTxtMessage(chatType[selectTab], selectItem, {
      msg: value,
    });
    this.emitEmpty();
  }

  emitEmpty() {
    this.setState({
      value: '',
      // height: 34
    });
    this.input.value = '';
    this.input.focus();
  }

  handleKey(e) {
    if (e.keyCode == 8 || e.keycode == 46) {
      // this.handleEmojiCancel()
    }
  }

  renderContactMenu(selectTab) {
    let tabs = null;
    if (selectTab == 'contact') {
      tabs = [
        ['0', `加入黑名单`, 'iconfont icon-circle-minus'],
        ['1', `删除好友`, 'iconfont icon-trash'],
      ];
    } else {
      // stranger
      tabs = [
        ['2', `加为好友`, 'anticon anticon-user-add'],
        ['3', `删除`, 'iconfont icon-trash'],
      ];
    }

    const tabsItem = tabs.map(([key, name, icon]) => (
      <Menu.Item key={key}>
        <i className={icon} style={{ fontSize: 20, marginRight: 12, verticalAlign: 'middle' }} />
        <span>
          <span>{name}</span>
        </span>
      </Menu.Item>
    ));
    const menuSettings = (
      <Menu className="x-header-ops__dropmenu" onClick={this.onMenuContactClick}>
        {tabsItem}
      </Menu>
    );

    return menuSettings;
  }

  onMenuContactClick({ key }) {
    // const { match } = this.props
    // const { selectItem, selectTab } = match.params
    // const search = history.location.search
    // switch (key) {
    // case '0':
    //     // block a friend
    //     this.props.doAddBlacklist(selectItem)
    //     history.push('/contact' + search)
    //     break
    // case '1':
    //     // delete a friend
    //     this.props.removeContact(selectItem)
    //     history.push('/contact' + search)
    //     break
    // case '2':
    //     // add a friend
    //     this.props.addContact(selectItem)
    //     message.success(`${I18n.t('addFriendMessage')}`)
    //     break
    // case '3':
    //     // delete
    //     this.props.deleteStranger(selectItem)
    //     history.push('/stranger' + search)
    //     break
    // default:
    // }
  }

  componentWillReceiveProps(nextProps) {
    // setTimeout(this.scollBottom, 0)
    // this.scollBottom()
  }

  componentDidUpdate() {
    this.scollBottom();
  }

  /**
   * componentDidMount
   *
   * @memberof Chat
   *
   * Note: get group members, muted members and group admins when in a group.
   * Especially recommend get muted members here.
   * Because, it will check current user in or not in muted list when sending a group message.
   */
  componentDidMount() {
    this.scollBottom();
  }

  componentWillUnmount() {
    if (this.timer) clearTimeout(this.timer);
  }

  handleModalClose = () => {
    this.props.closeInviteModal();
  };

  handleScroll = (e) => {
    const _this = this;
    if (e.target.scrollTop === 0) {
      // TODO: optimization needed
      setTimeout(function () {
        const offset = _this.props.messageList ? _this.props.messageList.length : 0;
        const { selectItem, selectTab } = _.get(_this.props, ['match', 'params'], {});
        const chatTypes = {
          contact: 'chat',
          group: 'groupchat',
          chatroom: 'chatroom',
          stranger: 'stranger',
        };
        const chatType = chatTypes[selectTab];

        // load more history message
        _this.props.fetchMessage(selectItem, chatType, offset, (res) => {
          // no more history when length less than 20
          if (res < PAGE_NUM) {
            _this.setState({
              isLoaded: true,
            });

            _this._not_scroll_bottom = false;
          }
        });

        _this._not_scroll_bottom = true;
      }, 500);
    }
  };
  ok = (id) => {
    this.props.deleteMessage(id, true);
  };

  handleHoverChange = (visible) => {
    this.setState({
      visible,
    });
  };

  onChange = (e) => {
    this.setState({
      checkedValue: e.target.value,
    });
  };

  sendIdCardMsg = async () => {
    const { selectItem, selectTab } = this.props.match && this.props.match.params;
    let chatType;
    if (selectTab === 'contact') {
      chatType = 'singleChat';
    } else if (selectTab === 'group') {
      chatType = 'groupchat';
    } else {
      chatType = 'chatroom';
    }

    const userId = this.state.checkedValue;

    let info = await this.props.getUserInfo(userId);
    info = info.data[userId];
    const msg = {
      userId,
      nick: info.nickname || '',
      avatar: info.avatarurl || '',
    };
    this.props.sendCustomMsg(chatType, selectItem, msg);
    this.setState({
      visible: false,
    });
  };
  onClickIdCard = async (data) => {
    const res = await this.props.getUserInfo(data.uid);
    const info = res.data[data.uid];
    this.userInfo = info;
    this.userInfo.userId = data.uid;
    // this.showEdit = data.uid == WebIM.conn.context.userId
    this.setState({
      showUserInfoMoadl: true,
    });
  };
  handleInfoModalClose = () => {
    this.setState({
      showUserInfoMoadl: false,
    });
  };

  handleMouseDown = (e) => {
    const { offset } = this.state;
    const startY = e.clientY;
    const move = (moveEvent) => {
      moveEvent.preventDefault();
      moveEvent.stopPropagation();
      let currentOffset = startY - moveEvent.clientY;
      currentOffset += offset;
      console.log('currentOffset', currentOffset);

      this.setState({ offset:currentOffset });
    };

    const up = (moveEvent) => {
      document.removeEventListener('mousemove', move, true);
      document.removeEventListener('mouseup', up, true);
    };
    document.addEventListener('mousemove', move, true);
    document.addEventListener('mouseup', up, true);
  };
  render() {
    // this.logger.info('chat component render')
    const {footHeight,offset} = this.state
    const {
      collapsed,
      match,
      // history,
      location,
      messageListByMid,
      confrModal,
      inviteModal,
    } = this.props;
    const messageList = [
        {
            "error": false,
            "errorCode": "",
            "errorText": "",
            "status": "sent",
            "id": "862065730667940196",
            "from": "112233",
            "to": "1122333",
            "toJid": "",
            "time": 1618280119016,
            "type": "chat",
            "body": {
                "type": "txt",
                "msg": "123"
            },
            "ext": {},
            "bySelf": false,
            "isUnread": 0
        },
        {
            "error": false,
            "errorCode": "",
            "errorText": "",
            "status": "sent",
            "id": 353607848751,
            "from": "",
            "to": "112233",
            "toJid": "863274033913792868",
            "time": 1618561448751,
            "type": "chat",
            "body": {
                "type": "txt",
                "msg": "在吗"
            },
            "ext": {},
            "bySelf": true,
            "isUnread": 0
        },
        {
            "error": false,
            "errorCode": "",
            "errorText": "",
            "status": "sending",
            "id": 353607946714,
            "from": "",
            "to": "112233",
            "toJid": "863274454283716964",
            "time": 1618561546715,
            "type": "chat",
            "body": {
                "type": "txt",
                "msg": "是的"
            },
            "ext": {},
            "bySelf": true,
            "isUnread": 0
        }
    ]
    const { selectItem, selectTab } = match && match.params;

    const back = () => {
      const redirectPath = `/${[selectTab].join('/')}${location.search}`;
      // history.push(redirectPath)
    };

    const name = selectItem;
    const webrtcButtons = [];
    let userinfos = {};
    if (selectTab === 'contact') {
      // const withInfoUsers = this.props.entities.roster.byName
      // userinfos = name = withInfoUsers ? withInfoUsers[selectItem]?.info.nickname: name
    }
    if (selectTab === 'group') {
      userinfos = this.props.entities.groupMember[selectItem]?.byName || {};
    }

    const content = () => {
      const radioStyle = {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      };

      const container = {
        height: '150px',
        overflowY: 'scroll',
      };
      let users = [];
      const list = [];
      let withInfoUsers = {};
      users = ['1122333'];
      withInfoUsers = {
        '1122333': {
          name: '1122333',
          subscription: 'both',
          jid: {
            appKey: 'easemob-demo#easeim',
            name: '112233',
            domain: 'easemob.com',
            clientResource: 'webim_1618556233314',
          },
          info: {},
        },
      };

      users.forEach((item, index) => {
        console.log('item', item);
        console.log('withInfoUsers', withInfoUsers);
        list.push(
          <Radio style={radioStyle} value={item} key={item}>
            {withInfoUsers[item].info.nickname || item}
          </Radio>,
        );
      });

      return (
        <div>
          <div style={container}>
            <Radio.Group onChange={this.onChange} value={this.state.checkedValue}>
              {list}
            </Radio.Group>
          </div>
          <Button onClick={this.sendIdCardMsg}>发送</Button>
        </div>
      );
    };
    return (
      <div className="x-chat">
        <div className="x-list-item x-chat-header">
          <div className="fl">
            {/* {collapsed
                            ? <Icon
                                type="arrow-left"
                                onClick={back}
                                style={{
                                    cursor: 'pointer',
                                    fontSize: 20,
                                    verticalAlign: 'middle',
                                    marginRight: 10
                                }}
                            />
                            : null} */}
            {name}
          </div>
          <div className="fr">
            <span style={{ color: '#8798a4', cursor: 'pointer' }}>
              {selectTab === 'contact' || selectTab === 'stranger' ? (
                <Dropdown
                  overlay={this.renderContactMenu(selectTab)}
                  placement="bottomRight"
                  trigger={['click']}
                >
                  {/* <Icon type="ellipsis" /> */}
                </Dropdown>
              ) : (
                <></>
              )}
            </span>
          </div>
        </div>
        <div className="x-chat-content" ref="x-chat-content" onScroll={this.handleScroll}>
          {/* fixed bug of messageList.map(...) */}
          {this.state.isLoaded && (
            <div
              style={{
                width: '150px',
                height: '30px',
                lineHeight: '30px',
                backgroundColor: '#888',
                color: '#fff',
                borderRadius: '15px',
                textAlign: 'center',
                margin: '10px auto',
              }}
            >
              没有更多消息啦~
            </div>
          )}
          {_.map(messageList, (message, i) => {
            if (i > 0) {
              if (message.id != messageList[i - 1].id) {
                return (
                  <ChatMessage
                    key={i}
                    fromNick={
                      selectTab == 'contact' ? userinfos : userinfos[message.from]?.info.nickname
                    }
                    onClickIdCard={this.onClickIdCard}
                    ok={this.ok}
                    {...message}
                  />
                );
              }
            } else {
              return (
                <ChatMessage
                  key={i}
                  fromNick={
                    selectTab == 'contact' ? userinfos : userinfos[message.from]?.info.nickname
                  }
                  onClickIdCard={this.onClickIdCard}
                  ok={this.ok}
                  {...message}
                />
              );
            }
          })}
        </div>

        <div className="x-chat-footer" style={{height:`calc(${footHeight} + ${offset}px)`}}>
        <div className="resizeVertical" onMouseDown={(e) => this.handleMouseDown(e)}></div>
          <div className="x-list-item x-chat-ops">
            {/* emoji */}
            {/* <div className="x-chat-ops-icon ib">
                            <ChatEmoji onClick={this.handleEmojiSelect} />
                        </div> */}
            {/* image upload */}
            <label
              htmlFor="uploadImage"
              className="x-chat-ops-icon ib"
              onClick={() => this.image && this.image.focus() && this.image.click()}
            >
              <FileImageFilled />
              <input
                id="uploadImage"
                ref={(node) => (this.image = node)}
                onChange={this.pictureChange}
                type="file"
                className="hide"
              />
            </label>
            {/*  file upload */}
            <label
              htmlFor="uploadFile"
              className="x-chat-ops-icon ib"
              onClick={() => this.file && this.file.focus() && this.file.click()}
            >
             <CalendarFilled />
              <input
                id="uploadFile"
                ref={(node) => (this.file = node)}
                onChange={this.fileChange}
                type="file"
                className="hide"
              />
            </label>
            {/* webrtc video && audio && 发送音频 */}
            {/* {webrtcButtons} */}
            {/* {WebIM.config.isWebRTC && <RecordAudio match={match}/>} */}
            {/* clear */}
            {/* <label htmlFor="clearMessage" className="x-chat-ops-icon ib" onClick={this.onClearMessage}>
                            <i className="icon iconfont icon-trash"></i>
                        </label> */}

            <Popover
              content={content()}
              title=""
              trigger="click"
              visible={this.state.visible}
              onVisibleChange={this.handleHoverChange}
            >
              {/* <Icon type="idcard" style={{padding:'0 15px'}} className="icon iconfont icon-trash"/> */}
            </Popover>
          </div>
          <div className="x-list-item x-chat-send">
            <div className="x-chat-send_box">
              <TextArea
                value={this.state.value}
                onChange={this.handleChange}
                onPressEnter={this.handleSend}
                placeholder="消息"
                ref={(node) => (this.input = node)}
              ></TextArea>
              <Row>
                <Col span={8} offset={16}>
                  <Button type="primary" danger shape="round" style={{ cursor: 'pointer' }}>
                    引导结束
                  </Button>
                  <Button
                    type="primary"
                    shape="round"
                    className="fontello icon-paper-plane"
                    onClick={this.handleSend}
                    style={{ cursor: 'pointer' }}
                  >
                    发送
                  </Button>
                </Col>
              </Row>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
export default Chat;
// export default connect(
//     (state, props) => ({
//         messageList: getTabMessages(state, props).TabMessageArray,
//         messageListByMid: state.entities.message.byMid,
//         inviteModal: state.callVideo.inviteModal,
//         callStatus: state.callVideo.callStatus,
//         entities: state.entities,
//         state: state
//     }),
//     dispatch => ({
//         switchRightSider: ({ rightSiderOffset }) => dispatch(GroupActions.switchRightSider({ rightSiderOffset })),
//         sendTxtMessage: (chatType, id, message) => dispatch(MessageActions.sendTxtMessage(chatType, id, message)),
//         deleteMessage: (id) => dispatch(MessageActions.deleteMessage(id, true)),
//         sendImgMessage: (chatType, id, message, source, callback) => dispatch(MessageActions.sendImgMessage(chatType, id, message, source, callback)),
//         sendFileMessage: (chatType, id, message, source, callback) => dispatch(MessageActions.sendFileMessage(chatType, id, message, source, callback)),
//         sendCustomMsg: (chatType, id, message) => dispatch(MessageActions.sendCustomMsg(chatType, id, message)),
//         clearMessage: (chatType, id) => dispatch(MessageActions.clearMessage(chatType, id)),
//         listGroupMemberAsync: opt => dispatch(GroupMemberActions.listGroupMemberAsync(opt)),
//         getMutedAsync: groupId => dispatch(GroupMemberActions.getMutedAsync(groupId)),
//         getGroupAdminAsync: groupId => dispatch(GroupMemberActions.getGroupAdminAsync(groupId)),
//         removeContact: id => dispatch(RosterActions.removeContact(id)),
//         addContact: id => dispatch(RosterActions.addContact(id)),
//         getUserInfo: id => dispatch(RosterActions.getUserInfo(id)),
//         deleteStranger: id => dispatch(StrangerActions.deleteStranger(id)),
//         doAddBlacklist: id => dispatch(BlacklistActions.doAddBlacklist(id)),
//         fetchMessage: (id, chatType, offset, cb) => dispatch(MessageActions.fetchMessage(id, chatType, offset, cb)),
//         showInviteModal: () => dispatch(VideoCallActions.showInviteModal()),
//         closeInviteModal: () => dispatch(VideoCallActions.closeInviteModal()),
//         updateConfr: (msg) => dispatch(VideoCallActions.updateConfr(msg)),
//         setCallStatus: (status) => dispatch(VideoCallActions.setCallStatus(status)),
//         cancelCall: (to) => dispatch(VideoCallActions.cancelCall(to)),
//         setGid: (gid) => dispatch(VideoCallActions.setGid(gid)),
//         hangup: () => dispatch(VideoCallActions.hangup())
//     })
// )(Chat)
